<?php

namespace app\admin\controller;

use app\admin\service\StoreService;
use think\facade\View;
use think\exception\ValidateException;
use app\store\model\Store;

class StoreController extends BaseController
{
    public function index()
    {   
        $goodsService = new StoreService();
        $list = $goodsService->getStoreList();

        return View::fetch('',['list' => $list]);
    }
    
    public function create()
    {   
        return View::fetch();
    }

    public function edit()
    {   
        $id = $this->request->get('id/d');

        $goodsService = new StoreService();
        $row = $goodsService->findStore($id);

        return View::fetch('',['row' => $row]);
    }

    public function save()
    {
        $param = $this->request->post();
        try {
            validate('StoreValidate')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }

        $goodsService = new StoreService();
        $id =  $goodsService->saveStore($param);
        
        return $id ? json(['code' => 1, '保存成功!']) : json(['code' => 0, '保存失败!']);

    }

    public function switch()
    {
        $param = $this->request->post();

        try {
            validate('StoreValidate.switch')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }

        Store::update($param);

        return json(['code' => 1, 'msg' => '更新成功!']);
    }


    public function update()
    {
        $param = $this->request->post();

        try {
            validate('StoreValidate.edit')->check($param);
        }catch(ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }

        $goodsService = new StoreService();
        $id =  $goodsService->updateStore($param);
        
        return $id ? json(['code' => 1, '保存成功!']) : json(['code' => 0, '保存失败!']);
    }


    public function delete()
    {
        $id = $this->request->get('id/d');
        $result = Store::destroy($id);

        return $result ?  json(['code' => 1, 'msg' => '删除成功!']) : json(['code' => 0, 'msg' => '删除失败!']);
    }
}